﻿using AutoMapper;
using MediatR;
using Microsoft.EntityFrameworkCore;
using RearLivestock.Common.Domains.Enum;
using RearLivestock.Common.Domains.hq;
using RearLivestock.Common.Domains.wbx;
using RearLivestock.Common.Dtos;
using RearLivestock.Common.Infrastructure.Interface;
using RearLivestock.RBAC.ErrorCodeEnum;
using System.Data;

namespace RearLivestock.Beginning.Api.Application.Command.PigArchives
{
    /// <summary>
    /// 猪只档案列表handler
    /// </summary>
    public class SearchPigBasicHandler : IRequestHandler<SearchPigBasicCommand, Result<PageResultDto<BasicDto>>>
    {
        private readonly IMapper mapper;

        /// <summary>
        /// 基本信息仓储
        /// </summary>
        private readonly IBaseRepository<BasicInformation> basicInformationrepository;

        /// <summary>
        /// 猪只类型仓储
        /// </summary>
        private readonly IBaseRepository<PigType> pigTyperepository;

        /// <summary>
        /// 栋舍仓储
        /// </summary>
        private readonly IBaseRepository<Bedrooms> bedroomsRepository;

        /// <summary>
        /// 栏位仓储
        /// </summary>
        private readonly IBaseRepository<Fields> fieldrepository;

        /// <summary>
        /// 品种仓储
        /// </summary>
        private readonly IBaseRepository<Varieties> varietiesrepository;

        /// <summary>
        /// 日志
        /// </summary>
        private readonly ILogger<SearchPigBasicHandler> _logger;
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="mapper"></param>
        /// <param name="basicInformationrepository"></param>
        /// <param name="pigTyperepository"></param>
        /// <param name="bedroomsRepository"></param>
        /// <param name="varietiesrepository"></param>
        /// <param name="fieldrepository"></param>
        /// <param name="logger"></param>
        public SearchPigBasicHandler(IMapper mapper, IBaseRepository<BasicInformation> basicInformationrepository, IBaseRepository<PigType> pigTyperepository, IBaseRepository<Bedrooms> bedroomsRepository, IBaseRepository<Varieties> varietiesrepository, IBaseRepository<Fields> fieldrepository, ILogger<SearchPigBasicHandler> logger)
        {
            this.mapper = mapper;
            this.basicInformationrepository = basicInformationrepository;
            this.pigTyperepository = pigTyperepository;
            this.bedroomsRepository = bedroomsRepository;
            this.varietiesrepository = varietiesrepository;
            this.fieldrepository = fieldrepository;
            _logger = logger;
        }
        /// <summary>
        /// 猪只档案列表
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<Result<PageResultDto<BasicDto>>> Handle(SearchPigBasicCommand request, CancellationToken cancellationToken)
        {
            var result = new Result<PageResultDto<BasicDto>>() { Code = (int)CommonErrorCode.Search };
            var page = new PageResultDto<BasicDto>() { TotalCount = 0, PageCount = 0, List = new List<BasicDto>() };
            try
            {
                var basic = await (from a in await basicInformationrepository.GetAll()
                                   join b in await varietiesrepository.GetAll()
                                   on a.VarietiesId equals b.VarietiesId
                                   join c in await pigTyperepository.GetAll()
                                   on a.PigTypeId equals c.PigTypeId
                                   join d in await bedroomsRepository.GetAll()
                                   on a.BedroomId equals d.BedroomId
                                   join e in await fieldrepository.GetAll()
                                   on a.FieldId equals e.FieldId
                                   select new BasicDto()
                                   {
                                       BasicInforId = a.BasicInforId,
                                       EarNumber = a.EarNumber,
                                       Electronicearlabel = a.Electronicearlabel,
                                       GeneticlevelEnums = a.GeneticlevelEnums,
                                       Gender = a.Gender,
                                       VarietiesId = b.VarietiesId,
                                       VarietiesName = b.VarietiesName,
                                       FatherEarNumber = a.FatherEarNumber,
                                       MotherEarNumber = a.MotherEarNumber,
                                       BirthDate = a.BirthDate,
                                       EntryDate = a.EntryDate,
                                       Birthplace = a.Birthplace,
                                       BirthWeight = a.BirthWeight,
                                       Remarks = a.Remarks,
                                       BirthStatus = a.BirthStatus,
                                       PigTypeId = a.PigTypeId,
                                       PigTypeName = c.PigTypeName,
                                       BedroomId = a.BedroomId,
                                       BedroomName = d.BedroomName,
                                       Presentstatus = a.Presentstatus,
                                       Reproductivestatus = a.Reproductivestatus,
                                       Productiongrade = a.Productiongrade,
                                       Saleslevel = a.Saleslevel,
                                       IsPrenatalCheckup = a.IsPrenatalCheckup,
                                       FieldId = e.FieldId,
                                       FieldName = e.FieldName
                                   }).Distinct().ToListAsync();
                //耳号模糊查
                if (!string.IsNullOrEmpty(request.EarNumber))
                {
                    basic = basic.Where(x => x.EarNumber.Contains(request.EarNumber)).ToList();
                }
                //电子耳标号模糊查
                if (!string.IsNullOrEmpty(request.Electronicearlabel))
                {
                    basic = basic.Where(x => x.Electronicearlabel.Contains(request.Electronicearlabel)).ToList();
                }
                //母亲耳号模糊查
                if (!string.IsNullOrEmpty(request.MotherEarNumber))
                {
                    basic = basic.Where(x => x.MotherEarNumber.Contains(request.MotherEarNumber)).ToList();
                }
                //父亲耳号模糊查
                if (!string.IsNullOrEmpty(request.FatherEarNumber))
                {
                    basic = basic.Where(x => x.FatherEarNumber.Contains(request.FatherEarNumber)).ToList();
                }
                //品种ID查询
                if (request.VarietiesId > 0)
                {
                    basic = basic.Where(x => x.VarietiesId == request.VarietiesId).ToList();
                }
                //姓名查询
                if (request.Gender > 0)
                {
                    basic = basic.Where(x => x.Gender == request.Gender).ToList();
                }
                //猪只类型ID查询
                if (request.PigTypeId > 0)
                {
                    basic = basic.Where(x => x.PigTypeId == request.PigTypeId).ToList();
                }
                //栋舍ID查询
                if (request.BedroomId > 0)
                {
                    basic = basic.Where(x => x.BedroomId == request.BedroomId).ToList();
                }
                //栏位ID查询
                if (request.FieldId > 0)
                {
                    basic = basic.Where(x => x.FieldId == request.FieldId).ToList();
                }
                //出生日期开始时间
                if (request.SDate != null)
                {
                    basic = basic.Where(x => x.BirthDate >= request.SDate).ToList();
                }
                //出生日期结束时间
                if (request.ODate != null)
                {
                    basic = basic.Where(x => x.BirthDate <= request.ODate).ToList();
                }
                //基因等级查询
                if (request.GeneticlevelEnums > 0)
                {
                    var geneticlevel = (GeneticlevelEnums)request.GeneticlevelEnums;
                    basic = basic.Where(x => x.GeneticlevelEnums == geneticlevel).ToList();
                }
                //在场状态查询
                if (request.Presentstatus > 0)
                {
                    var presentstatus = (PresentstatusEnums)request.Presentstatus;
                    basic = basic.Where(x => x.Presentstatus == presentstatus).ToList();
                }
                //繁殖状态查询
                if (request.Reproductivestatus > 0)
                {
                    var reproductivestatus = (ReproductivestatusEnums)request.Reproductivestatus;
                    basic = basic.Where(x => x.Reproductivestatus == reproductivestatus).ToList();
                }
                //生产等级查询
                if (request.Productiongrade > 0)
                {
                    var productiongrade = (ProductiongradeEnums)request.Productiongrade;
                    basic = basic.Where(x => x.Productiongrade == productiongrade).ToList();
                }
                //销售等级
                if (request.Saleslevel > 0)
                {
                    var saleslevel = (SaleslevelEnums)request.Saleslevel;
                    basic = basic.Where(x => x.Saleslevel == saleslevel).ToList();
                }
                page.TotalCount = basic.Count();
                page.PageCount = (int)Math.Ceiling(page.TotalCount * 1.0 / request.PageSize);
                page.List = basic.OrderBy(x => x.BasicInforId).Skip((request.PageIndex - 1) * request.PageSize).Take(request.PageSize).ToList();
                result.Data = page;
                result.Msg = "猪只档案显示成功";
            }
            catch (Exception ex)
            {
                _logger.LogError("猪只档案显示失败" + ex.Message);
                throw;
            }
            return result;
        }
    }
}
